package db;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class RowSet
{
    //Package scope members
    List<Row> rows;
    String[] names;
    HashMap<String, Integer> indices;
    Connector connector;

    //Package scope constructors. All constructors in this class should not be public.
    public RowSet(ArrayList<Row> list, final RowSet template)
    {
        this.names = template.names;
        this.indices = template.indices;
        this.rows = list;
    }

    public RowSet(ArrayList<Row> list, String[] names, HashMap<String, Integer> indices)
    {
        this.names = names;
        this.indices = indices;
        this.rows = list;
    }

    public RowSet(RowSet... rowSets)
    {
        this.names = rowSets[0].names;
        this.indices = rowSets[0].indices;
        this.rows = new ArrayList<Row>();
        for (RowSet item : rowSets)
        {
            for (Row row : item.rows)
            {
                this.rows.add(row);
            }
        }
    }

    public RowSet(ResultSet rs) throws SQLException
    {
        indices = new HashMap<String, Integer>();
        ResultSetMetaData meta = rs.getMetaData();
        int columnCount=meta.getColumnCount();
        this.names = new String[columnCount];
        int index=0;
        for (int i = 1; i <= columnCount; i++)
        {
        	String name=meta.getColumnLabel(i);
        	names[i - 1] = name;
        	if (indices.containsKey(name)==false)
        	{
        		indices.put(name, index);
        	}
    		index++;
        }

        this.rows = new ArrayList<Row>();
        while (rs.next())
        {
            Row row = new Row(indices, names);
            for (int i = 1; i <= columnCount; i++)
            {
                 row.values[i - 1]=rs.getObject(i);
            }
            this.rows.add(row);
        }
    }
    public RowSet(Connector connector,ResultSet rs) throws SQLException
    {
        this(rs);
        this.connector=connector;
    }

    public String getFieldName(int index)
    {
        return names[index];
    }
    
    public Connector getConnector()
    {
        return connector;
    }
    
    public int getFields()
    {
        return names.length;
    }

    public List<Row> getRows()
    {
        return rows;
    }

    public Integer getFieldIndex(String fieldName)
    {
        return indices.get(fieldName);
    }
}
